#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
照片 → 线条素描（抖音糯米code）
"""
from PIL import Image, ImageOps, ImageFilter, ImageTk
import numpy as np
import tkinter as tk

# ---------- 1. 读图 ----------
img_path = r'E:\code\Nuomi\ren.png'   # ←←← 换成你的路径
img_rgb = Image.open(img_path)

# ---------- 2. 处理 ----------
gray = img_rgb.convert('L')
invert = ImageOps.invert(gray)
blur = invert.filter(ImageFilter.GaussianBlur(radius=5))

gray_arr = np.array(gray, dtype=np.float32)
blur_arr = np.array(blur, dtype=np.float32)

divisor = 256.0 - blur_arr
divisor[divisor == 0] = 1
sketch_arr = gray_arr * 255.0 / divisor
sketch_arr = np.clip(sketch_arr, 0, 255).astype(np.uint8)

sketch = Image.fromarray(sketch_arr)
sketch.save('sketch_result.png')
print('已保存为 sketch_result.png')

# ---------- 3. 工具：等比例缩放到屏幕(抖音糯米code) ----------
def fit_to_screen(img, root, margin=40):
    sw, sh = img.size
    # 现在 root 已经存在，可以正确拿屏幕大小
    max_w = root.winfo_screenwidth() - margin
    max_h = root.winfo_screenheight() - margin
    scale = min(max_w / sw, max_h / sh, 1.0)  # 1.0 保证不放大
    new_size = (int(sw * scale), int(sh * scale))
    return img.resize(new_size, Image.LANCZOS)


# ---------- 4. 闪图窗口 ----------
class FlashWindow:
    def __init__(self, img_original, img_sketch):
        self.root = tk.Tk()
        self.root.title('照片转素描（抖音糯米code）')

        # 先让窗口存在，再缩放图片
        self.orig_pil = fit_to_screen(img_original, self.root)
        self.sk_pil   = fit_to_screen(img_sketch,   self.root)

        w, h = self.orig_pil.size
        self.root.geometry(f'{w}x{h}')
        self.canvas = tk.Canvas(self.root, width=w, height=h, highlightthickness=0)
        self.canvas.pack(fill='both', expand=True)

        self.orig = ImageTk.PhotoImage(self.orig_pil)
        self.sk   = ImageTk.PhotoImage(self.sk_pil)

        self.canvas.create_image(0, 0, anchor='nw', image=self.orig)
        self.root.after(1500, self.switch)
        self.root.bind('<Key>', lambda e: self.root.destroy())
        self.root.protocol('WM_DELETE_WINDOW', self.root.destroy)

    def switch(self):
        self.canvas.create_image(0, 0, anchor='nw', image=self.sk)

    def run(self):
        self.root.mainloop()

# ---------- 5. 运行 ----------
FlashWindow(img_rgb, sketch).run()